import sys, re
import pyjavaproperties


class adprops(pyjavaproperties.Properties):
    def __init__(self, fname, grouped = True):
        super(adprops, self).__init__()
        self.LoadFile(fname)
        self.curlies = re.compile("{(.+?)}")
        self.grouped = grouped
        self.PropsSubstituteAll()

    def LoadFile(self, fname):
        try:
            with open(fname) as fp:
                super(adprops, self).load(fp)
        except IOError:
            print("can't open '%s'\n" % fname)
            sys.exit(1)

    def PropsSubstituteLine(self, key, prefixRe = None):
        mv = self.curlies.findall(self._props[key])
        for f in mv:
            back = re.compile(f + "$")
            for k2, i2 in self._props.items():
                if back.search(k2) and (not prefixRe or prefixRe.match(k2)):
                    self._props[key] = self._props[key].replace('{' + f + '}', i2, 1)

    def PropsSubstituteAll(self, fromPrefix = None):
        if fromPrefix is not None:
            prefixRe = re.compile('^' + fromPrefix)
        else:
            prefixRe = None
        for key in self._props.keys():
            self.PropsSubstituteLine(key, prefixRe)

    def __contains__(self, key):
        return key in self._props

